package validate

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/util/gvalid"
)

// RuleRegisterUser 注册用户验证规则
func RuleRegisterUser() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`valid-user-id`:  RuleValidUserByUid,
		`user-exists-id`: RuleUserExistsUid,
	})
}

// RuleValidUserByUid 验证有效用户信息
func RuleValidUserByUid(ctx context.Context, in gvalid.RuleFuncInput) error {
	// 验证类，值为空，返回Nil，需结合required使用
	if in.Value.Uint() == 0 {
		return nil
	}

	// 获取用户信息
	detail, err := service.User().ProcessUserByUid(ctx, in.Value.Uint())
	if err != nil {
		return err
	}

	// 是否禁用
	if enums.UserStatus(detail.Status) != enums.UserStatusOk {
		return exception.Newf(`用户%s%s`, detail.Nickname, enums.UserStatus(detail.Status).Fmt())
	}
	return nil
}

// RuleUserExistsUid 通过用户ID检测用户是否存在
func RuleUserExistsUid(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 验证用户是否存在
	if !service.User().CheckUserExistsByUid(ctx, in.Value.Uint()) {
		return exception.New(`用户不存在`)
	}
	return nil
}
